package com.example.remoteassistance;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

//显示活动
public class DisplayActivity extends AppCompatActivity implements Runnable {

    private static final String TAG = "DisplayActivity";

    private String mid;
    private String sid;

    private int mDisplayWidth;
    private int mDisplayHeight;

    private float mWidthRatio;
    private float mHeightRatio;

    private VideoDecoder mVideoDecoder;

    private MessageWebSocketClient mMessageWebSocketClient;
    private MessageWebSocketService mMessageWebSocketService;
    private final ServiceConnection mMessageWebSocketServiceConnection = new ServiceConnection() {
        //绑定数据传输websocket
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mMessageWebSocketService = ((MessageWebSocketService.MessageWebSocketBinder) iBinder).getService();
            mMessageWebSocketClient = MessageWebSocketService.mMessageWebSocketClient;
            Log.d(TAG, "onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            if (mMessageWebSocketService != null) {
                mMessageWebSocketService = null;
            }
            Log.d(TAG, "onServiceDisconnected");
        }
    };

    private boolean isTouchUp = false;
    private boolean isTouchDown = false;
    private boolean isTouching = false;
    private Map<String, Integer> touch = new HashMap<String, Integer>();

    private void startTouch() {
        isTouching = true;
        new Thread(this).start();
    }

    private void stopTouch() {
        isTouching = false;
    }

    //触摸事件
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            //获取触摸起始坐标
            case MotionEvent.ACTION_DOWN:
                int staX = (int) (event.getX() * mWidthRatio);
                int staY = (int) (event.getY() * mHeightRatio);
                touch.put("staX", staX);
                touch.put("staY", staY);
                isTouchDown = true;
                Log.d(TAG, "staPos:("+staX+","+staY+")");
                break;
            //获取触摸结束坐标
            case MotionEvent.ACTION_UP:
                int endX = (int) (event.getX() * mWidthRatio);
                int endY = (int) (event.getY() * mHeightRatio);
                touch.put("endX", endX);
                touch.put("endY", endY);
                isTouchUp = true;
                Log.d(TAG, "endPos:("+endX+","+endY+")");
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void run() {
        //判断是否正在触摸
        while (isTouching) {
            //判断是否完整的触摸过程
            if (isTouchDown && isTouchUp) {
                Log.d(TAG, "isTouchDown && isTouchUp is true");
                //打包数据
                ObjectMapper mapper = new ObjectMapper();
                MessagePacket packet = new MessagePacket();
                String msg = null;
                packet.setMsg("touch");
                packet.setMid(getMid());
                packet.setSid(getSid());
                packet.setMap(touch);
                try {
                    msg = mapper.writeValueAsString(packet);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                //发送数据包
                mMessageWebSocketClient.send(msg);
                isTouchDown = false;
                isTouchUp = false;
                touch.clear();
            }
        }
        Log.d(TAG, "touch thread is ending");
    }

    //数据传输广播接收器
    private class MessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra("message");
            try {
                ObjectMapper mapper = new ObjectMapper();
                MessagePacket packet = mapper.readValue(message, MessagePacket.class);
                //判断接收命令
                switch (packet.getMsg()) {
                    //屏幕尺寸
                    case "size":
                        int recordWidth = packet.getMap().get("width");
                        int recordHeight = packet.getMap().get("height");
                        setWidthRatio(recordWidth, mDisplayWidth);
                        setHeightRatio(recordHeight, mDisplayHeight);
                        Log.d(TAG, "RecordScreenSize:"+recordWidth+"*"+recordHeight);
                        Log.d(TAG, "DisplayScreenSize:"+mDisplayWidth+"*"+mDisplayHeight);
                        Log.d(TAG, "SizeRatio:"+mWidthRatio+"*"+mHeightRatio);
                        break;
                    default:
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d(TAG, "onReceive");
        }
    }

    //注册数据传输广播接收器
    private void registerMessageBroadcastReceiver() {
        MessageBroadcastReceiver messageBroadcastReceiver = new MessageBroadcastReceiver();
        IntentFilter filter = new IntentFilter("com.example.remoteassistance.websocket.message");
        registerReceiver(messageBroadcastReceiver, filter);
    }

    private StreamWebSocketClient mStreamWebSocketClient;
    private StreamWebSocketService mStreamWebSocketService;
    private final ServiceConnection mStreamWebSocketServiceConnection = new ServiceConnection() {
        //绑定视频流websocket服务
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mStreamWebSocketService = ((StreamWebSocketService.StreamWebSocketBinder) iBinder).getService();
            mStreamWebSocketClient = StreamWebSocketService.mStreamWebSocketClient;
            Log.d(TAG, "onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            if (mStreamWebSocketService != null) {
                mStreamWebSocketService = null;
            }
            Log.d(TAG, "onServiceDisconnected");
        }
    };

    //视频流广播接收器
    private class StreamBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            byte[] bytes = intent.getByteArrayExtra("bytes");
            onDecodeData(bytes);
        }
    }

    //注册视频流广播接收器
    private void registerStreamBroadcastReceiver() {
        StreamBroadcastReceiver streamBroadcastReceiver = new StreamBroadcastReceiver();
        IntentFilter filter = new IntentFilter("com.example.remoteassistance.websocket.stream");
        registerReceiver(streamBroadcastReceiver, filter);
    }

    //初始化界面
    private void initViews() {
        hideActionBar();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.sv_screen);
        surfaceView.getHolder().addCallback(
                new SurfaceHolder.Callback() {
                    @Override
                    public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
                        mVideoDecoder = new VideoDecoder(surfaceHolder.getSurface(), mDisplayWidth, mDisplayHeight);
//                        startDisplay();
                        startTouch();
                    }

                    @Override
                    public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

                    }

                    @Override
                    public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
//                        stopDisplay();
                        stopTouch();
                    }
                }
        );
    }

    //隐藏导航栏
    private void hideActionBar() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
    }

    //启动显示
    private void startDisplay() {
        if (mVideoDecoder != null) {
            mVideoDecoder.start();
            Log.d(TAG, "startDisplay");
        }
    }

    //停止显示
    private void stopDisplay() {
        if (mVideoDecoder != null) {
            mVideoDecoder.stop();
            Log.d(TAG, "stopDisplay");
        }
    }

    //销毁显示
    private void destroyDisplay() {
        if (mVideoDecoder != null) {
            mVideoDecoder.destroy();
            Log.d(TAG, "destroyDisplay");
        }
    }

    //解码视频数据
    private void onDecodeData(byte[] bytes) {
        if (mVideoDecoder != null) {
            if (bytes != null && bytes.length != 0) {
//                mVideoDecoder.setData(bytes);
                mVideoDecoder.decodeData(bytes);
            }
        }
    }

    //获取屏幕尺寸
    private Map<String, Integer> getDisplayScreenSize() {
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getRealMetrics(metrics);
        Map<String, Integer> size = new HashMap<String, Integer>();
        size.put("width", metrics.widthPixels);
        size.put("height", metrics.heightPixels);
        return size;
    }

    //设置屏幕宽度比值
    private void setWidthRatio(int recordWidth, int displayWidth) {
        mWidthRatio = (float) recordWidth / (float) displayWidth;
    }

    //设置屏幕高度比值
    private void setHeightRatio(int recordHeight, int displayHeight) {
        mHeightRatio = (float) recordHeight / (float) displayHeight;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);

        //获取屏幕尺寸
        Map<String, Integer> size = getDisplayScreenSize();
        mDisplayWidth = size.get("width");
        mDisplayHeight = size.get("height");

        //获取主机和从机id
        Intent intent = getIntent();
        setMid(intent.getStringExtra("mid"));
        setSid(intent.getStringExtra("sid"));

        //绑定数据传输和视频流websocket
        bindMessageWebSocketService();
        bindStreamWebSocketService();

        //注册数据传输和视频流广播接收器
        registerMessageBroadcastReceiver();
        registerStreamBroadcastReceiver();

        //初始化界面
        initViews();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyDisplay();
    }

    //绑定数据传输websocket服务
    private void bindMessageWebSocketService() {
        Intent intent = new Intent(DisplayActivity.this, MessageWebSocketService.class);
        intent.putExtra("mid", getMid());
        bindService(intent, mMessageWebSocketServiceConnection, BIND_AUTO_CREATE);
    }

    //绑定视频流websocket服务
    private void bindStreamWebSocketService() {
        Intent intent = new Intent(DisplayActivity.this, StreamWebSocketService.class);
        intent.putExtra("mid", getMid()+"-stream");
        bindService(intent, mStreamWebSocketServiceConnection, BIND_AUTO_CREATE);
    }

    private void setMid(String mid) {
        this.mid = mid;
    }

    private String getMid() {
        return mid;
    }

    private void setSid(String sid) {
        this.sid = sid;
    }

    private String getSid() {
        return sid;
    }
}